package cn.wit.baoyan.interceptor;


import cn.wit.utils.pojo.SysUser;
import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            String json = JSONUtils.toJSONString("未进行登录");
            // 设置响应状态码为401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // 设置响应内容为JSON格式的错误信息
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
            return false;
        }
        SysUser user = (SysUser) redisTemplate.opsForValue().get(token);
        if (user == null) {
            String json = JSONUtils.toJSONString("未进行登录");
            // 设置响应状态码为401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // 设置响应内容为JSON格式的错误信息
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
            return false;
        }
        return true;
    }
}
//111